package cn.kgc.shiro03.service.impl;

import cn.kgc.shiro03.dto.UserPageDTO;
import cn.kgc.shiro03.entity.*;
import cn.kgc.shiro03.mapper.*;
import cn.kgc.shiro03.util.CodeMsg;
import cn.kgc.shiro03.util.ResponseResult;
import cn.kgc.shiro03.util.SaltUtil;
import cn.kgc.shiro03.util.TreeUtil;
import cn.kgc.shiro03.vo.PermissionVO;
import cn.kgc.shiro03.vo.UserVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.kgc.shiro03.service.UserService;
import com.mysql.jdbc.StringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.*;

import java.util.stream.Collectors;


/**
 *
 */
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired(required = false)
    private UserMapper userMapper;

    @Autowired(required = false)
    private UserRoleMapper userRoleMapper;

    @Autowired(required = false)
    private RoleMapper roleMapper;

    @Autowired(required = false)
    private RolePersMapper rolePersMapper;

    @Autowired(required = false)
    private PermissionMapper permissionMapper;

    @Override
    public ResponseResult selectPage(UserPageDTO userPageDTO) {

        Integer page = userPageDTO.getPage();
        Integer limit = userPageDTO.getLimit();
        Page<User> userPage = new Page<>(page, limit);

        LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda();
        lambda.like(!StringUtils.isEmptyOrWhitespaceOnly(userPageDTO.getUsername()), User::getUsername, userPageDTO.getUsername())
                .like(!StringUtils.isEmptyOrWhitespaceOnly(userPageDTO.getCity()), User::getCity, userPageDTO.getCity());
        userMapper.selectPage(userPage, lambda);

        List<User> users = userPage.getRecords();
        long total = userPage.getTotal();

        //  User  ->  UserVO   ->  roles

        // 遍历 users  查询用户具有的角色
        ArrayList<UserVO> userVOS = new ArrayList<>();
        users.forEach(user -> {
            Integer userId = user.getId();
            // 根据用户的id  查询用户的角色id   user_role   -> UserRole

            QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
            userRoleQueryWrapper.eq("user_id", userId);
            List<UserRole> userRoles = userRoleMapper.selectList(userRoleQueryWrapper);

            // 遍历userRoles   获取所有角色id
            ArrayList<Integer> ids = new ArrayList<>();
            userRoles.forEach(userRole -> {
                Integer roleId = userRole.getRoleId();
                ids.add(roleId);
            });

            // 根据用户的id 查询 用户的角色信息
            List<Role> roles = roleMapper.selectBatchIds(ids);
            // 获取用户的角色名
            ArrayList<String> roleNames = new ArrayList<>();
            roles.forEach(role -> {
                roleNames.add(role.getComments());
            });

            UserVO userVO = new UserVO();
            // 对象的copy
            BeanUtils.copyProperties(user, userVO);
            userVO.setRoles(roleNames);

            userVOS.add(userVO);

        });

        // 封装响应数据
        ResponseResult responseResult = new ResponseResult();
        responseResult.setData(userVOS);
        responseResult.setMsg(CodeMsg.SELECT_SUCCESS.getMsg());
        responseResult.setCode(CodeMsg.SELECT_SUCCESS.getCode());
        responseResult.setCount(total);

        return responseResult;
    }

    @Override
    public ResponseResult updateUserState(User user) {

        ResponseResult responseResult = new ResponseResult();
        userMapper.updateById(user);
        responseResult.setCode(CodeMsg.UPDATE_SUCCESS.getCode());
        responseResult.setMsg(CodeMsg.UPDATE_SUCCESS.getMsg());
        return responseResult;
    }

    @Override
    public ResponseResult addUser(UserVO userVO) {

        ResponseResult responseResult = new ResponseResult();
        //将用户信息 添加到user表
        User user = new User();
        BeanUtils.copyProperties(userVO, user);
        // 判定用户是否存在
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", user.getUsername());
        User usr = userMapper.selectOne(userQueryWrapper);

        if (usr == null) {
            //密码加密
            String salt = SaltUtil.getSalt(8);
            user.setSalt(salt);
            String md5Pwd = new Md5Hash("888888", salt).toHex();
            user.setPassword(md5Pwd);

            userMapper.insert(user);
            //将用户角色信息 添加到user_role表
            List<String> roles = userVO.getRoles();
            //根据角色查询角色id
            LambdaQueryWrapper<Role> lambda = new QueryWrapper<Role>().lambda();
            lambda.in(Role::getComments, roles.toArray());
            List<Role> rls = roleMapper.selectList(lambda);

            //添加到user_role表
            Integer userId = user.getId();
            rls.forEach(rl -> {

                UserRole userRole = new UserRole();
                userRole.setRoleId(rl.getRoleId());
                userRole.setUserId(userId);
                userRoleMapper.insert(userRole);
            });

            responseResult.setMsg(CodeMsg.ADD_SUCCESS.getMsg());
            responseResult.setCode(CodeMsg.ADD_SUCCESS.getCode());

        } else {
            responseResult.setCode(CodeMsg.USER_EXIST.getCode());
            responseResult.setMsg(CodeMsg.USER_EXIST.getMsg());
        }
        return responseResult;
    }

    @Override
    public ResponseResult getUserVOById(Integer id) {

        // 查询用户基础信息
        User user = userMapper.selectById(id);
        //  查询用户的角色id
        QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
        userRoleQueryWrapper.eq("user_id", id);
        List<UserRole> userRoles = userRoleMapper.selectList(userRoleQueryWrapper);
        // 遍历集合 获取角色id
        ArrayList<Integer> roleIds = new ArrayList<>();
        userRoles.forEach(userRole -> {
            roleIds.add(userRole.getRoleId());
        });

        System.out.println("roleIds = " + roleIds);

        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        userVO.setRoleIds(roleIds);

        System.out.println("userVO = " + userVO);

        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(CodeMsg.SELECT_SUCCESS.getCode());
        responseResult.setMsg(CodeMsg.SELECT_SUCCESS.getMsg());
        responseResult.setData(userVO);

        return responseResult;
    }

    @Override
    public ResponseResult updateUser(UserVO userVO) {

        //  用户表  根据用户id 更新用户信息
        User user = new User();
        BeanUtils.copyProperties(userVO, user);
        userMapper.updateById(user);

        // 用户角色关联表    删除当前用于的所有角色信息 user_role   添加新的角色信息
        Integer userId = user.getId();
        LambdaQueryWrapper<UserRole> lambda = new QueryWrapper<UserRole>().lambda();
        lambda.eq(UserRole::getUserId, userId);
        userRoleMapper.delete(lambda);

        List<Integer> roleIds = userVO.getRoleIds();
        roleIds.forEach(roleId -> {
            UserRole userRole = new UserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(roleId);
            userRoleMapper.insert(userRole);
        });

        ResponseResult responseResult = new ResponseResult();
        responseResult.setMsg(CodeMsg.UPDATE_SUCCESS.getMsg());
        responseResult.setCode(CodeMsg.UPDATE_SUCCESS.getCode());

        return responseResult;
    }

    @Override
    public ResponseResult deleteUser(String ids) {

        String[] idsStr = ids.split(",");

        ArrayList<Integer> intIds = new ArrayList<>();
        for (String s : idsStr) {
            intIds.add(Integer.valueOf(s));
        }

        userMapper.deleteBatchIds(intIds);
        QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
        userRoleQueryWrapper.in("user_id", intIds);
        userRoleMapper.delete(userRoleQueryWrapper);

        ResponseResult responseResult = new ResponseResult();
        responseResult.setMsg(CodeMsg.DELETE_SUCCESS.getMsg());
        responseResult.setCode(CodeMsg.DELETE_SUCCESS.getCode());
        return responseResult;
    }

    @Override
    public Map<String, Object> loadMenu(String username) {
        // menu {homeInfo:{},logoInfo:{},menuInfo:[{},{}]}
        Map<String, Object> map = new HashMap<>(16);
        //homeInfo
        Map<String, Object> home = new HashMap<>(16);
        //logoInfo
        Map<String, Object> logo = new HashMap<>(16);

        //数据初始化
        home.put("title", "首页");
        home.put("href", "https://www.8zt.cc");
        map.put("homeInfo", home);

        logo.put("title", "KGC后台");
        logo.put("image", "images/logo.png");
        map.put("logoInfo", logo);

        // 根据用户名 查询用户的权限信息  -> 将查询的数据数据结构调整为 tree
        // 1.用户名查询用户id  id
        LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda();
        lambda.eq(User::getUsername, username);
        User user = userMapper.selectOne(lambda);
        Integer userId = user.getId();


        // 2.根据用户id 查询 角色id
        LambdaQueryWrapper<UserRole> lambd = new QueryWrapper<UserRole>().lambda();
        lambd.eq(UserRole::getUserId, userId);
        List<UserRole> userRoles = userRoleMapper.selectList(lambd);

        List<Integer> roleIds = userRoles.stream().map(userRole -> {
            return userRole.getRoleId();
        }).collect(Collectors.toList());


        // 3.根据角色id  查询权限id
        QueryWrapper<RolePers> rolePersQueryWrapper = new QueryWrapper<>();
        rolePersQueryWrapper.in("role_id", roleIds);
        List<RolePers> rolePers = rolePersMapper.selectList(rolePersQueryWrapper);

        List<Integer> perIds = rolePers.stream().map(rp -> {
            return rp.getPerId();
        }).collect(Collectors.toList());

        // 4.根据权限id 查询权限的详细信息    目录  菜单
        LambdaQueryWrapper<Permission> perLambda = new QueryWrapper<Permission>().lambda();
        perLambda.in(Permission::getId, perIds)
                .in(Permission::getIsMenu, Arrays.asList(0, 1));
        List<Permission> permissions = permissionMapper.selectList(perLambda);

        List<PermissionVO> permissionVOs = permissions.stream().map(permission -> {
            PermissionVO permissionVO = new PermissionVO();
            BeanUtils.copyProperties(permission, permissionVO);
            return permissionVO;
        }).collect(Collectors.toList());

        // 5.将查询的数据数据结构调整为 tree
        List<PermissionVO> permissionVOS = TreeUtil.toTree(permissionVOs, 0);
        map.put("menuInfo", permissionVOS);

        return map;
    }

}




